// pages/member/rankingListSecond/rankingListSecond.js
var app = getApp();
const skinBehavior = require('../../../../utils/themeSkin/skinBehavior');

Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    is_queue_process: 0,
    language: "",
    show1: false,
    show2: false,
    show3: false,
    show4: false,
    nickname: "",
    avatar: "",
    summarizing: {
      goods_queue_count: 0,
      store_queue_count: 0,
      cashier_queue_count: 0,
    },
    getDataApi: "",
    rewardList: [],
    activeName: "shop",
    chooseName: "queue",
    status: "",
    chooseId: "",
    chooseRatio: "",
    msg: "",
    typeData: {
      pop_ups: {}
    },
    WXtitle: "",
    items: {}, // 显示完整信息
    // more
    isLoadMore: true,
    page: 0,
    total_page: 0,
    // 兑换类型 1=>积分 2=>爱心值
    type: "",
    convertType: "",
    convertTypeId: 0,
    convertTypeUnit: 0,
    convertTypeExchange_count: 0,
    exchangeLogs: {},
    show_reward_ratio: 1,
    is_awaiting_rewards: 1,
    showeforeSurePop: false,
    checkedSurePop: false,
    rule_desc: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // if (app.globalData.STORE_ID) {
    // 这是门店独立模板新增的共享链二开
    this.get_statistics_STORE();
    // } else {
    //   this.checkrouter();
    //   this.getTitle();
    //   this.getUser();
    //   this.getHomeInfo();
    // }
    let {
      plugin_setting: {
        share_chain: {
          show_reward_ratio
        }
      }
    } = wx.getStorageSync("yz_basic_info") || {};
    this.setData({
      show_reward_ratio: Number(show_reward_ratio)
    })
  },
  onClickVal(e) {
    let {
      name,
      val
    } = e.currentTarget.dataset;
    this.setData({
      [name]: val
    });
  },
  checkrouter() {
    try {
      // 推广中心是否开启该功能，没开启跳转到指定路径
      let basic_info = wx.getStorageSync("yz_basic_info");
      let stop_info = basic_info.popularize_page.mini.vue_route;
      for (let i = 0; i < stop_info.length; i++) {
        if (stop_info[i] == "RewardQueue") {
          console.log(basic_info.popularize_page.mini.mini_url + "跳转的路径");

          wx.showToast({
            title: "未开启推广权限",
            duration: 1000,
            icon: "none",
            success: function () {
              setTimeout(() => {
                wx.redirectTo({
                  url: basic_info.popularize_page.mini.mini_url,
                });
              }, 1000);
            },
          });
          return;
        }
      }
    } catch (e) {
      console.log(e);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      wx.showToast({
        title: "没有更多数据",
        icon: "none",
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  toDetail() {
    wx.navigateTo({
      url: "/packageB/member/enterprise/reward_detail/reward_detail",
    });
  },
  toProcess(item) {
    let items = item.currentTarget.dataset.item || item.target.dataset.item;
    wx.navigateTo({
      url: "/packageB/member/enterprise/RewardProcess/RewardProcess" + "?source_code=" + this.data.activeName + "&queue_id=" + items.id,
    });
  },
  showComplete(obj) {
    let item = obj.currentTarget.dataset.item || obj.target.dataset.item;
    item.show = true;
    let arr = this.data.rewardList;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == item.id) {
        arr[i].show = true;
      }
    }
    this.setData({
      rewardList: arr,
    });
  },
  ruleShowTap() {
    this.setData({
      ruleShow: true
    })
  },
  ruleShowClose() {
    this.setData({
      ruleShow: false
    })
  },
  show2Close() {
    this.setData({
      show2: false,
    })
  },
  // 点击蒙层时触发
  leaveOut() {
    this.setData({
      show3: false,
    });
  },
  getTitle() {
    // 兑换操作
    let urlStr = app.getNetAddresss("plugin.share-chain.frontend.plugin-name.index");
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          res.data = res.data.data;
          wx.setNavigationBarTitle({
            title: res.data.plugin_name ? res.data.plugin_name : "",
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  chooseType(convertType) {
    // 根据选择类型显示弹框
    let level = convertType.target.dataset.point || convertType.currentTarget.dataset.point;
    let typeData = this.data.typeData;
    if (level.code === 1) {
      this.setData({
        convertType: typeData.modules.point.name,
        convertTypeId: typeData.modules.point.code,
        convertTypeUnit: typeData.modules.point.unit,
        convertTypeExchange_count: typeData.modules.point.exchange_count,
      });
    } else if (level.code === 2) {
      this.setData({
        convertType: typeData.modules.love.name,
        convertTypeId: typeData.modules.love.code,
        convertTypeUnit: typeData.modules.love.unit,
        convertTypeExchange_count: typeData.modules.love.exchange_count,
      });
    }
  },
  exchange(item) {
    let items = item.currentTarget.dataset.item || item.target.dataset.item;
    this.setData({
      chooseId: items.id,
      convertType: "",
      convertTypeId: 0,
      convertTypeUnit: 0,
      convertTypeExchange_count: 0,
    });
    let urlStr = app.getNetAddresss("plugin.share-chain.frontend.exchange.index");
    urlStr += "&source_code=" + this.data.activeName + "&queue_id=" + items.id;
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          res.data = res.data.data;
          this.setData({
            show3: true,
            typeData: res.data,
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  beforeSureExchange() {
    if (this.data.typeData.modules && !this.data.convertTypeId) {
      wx.showToast({
        title: '请选择兑换类型',
        icon: "none",
      });
      return;
    }
    // 兑换前确认
    if (this.data.typeData.pop_ups && this.data.typeData.pop_ups.is_pop_ups) {
      // 显示弹窗
      this.setData({
        showeforeSurePop: true
      });
    } else {
      this.SureExchange();
    }
  },
  SureExchange() {
    if (this.data.showeforeSurePop && !this.data.checkedSurePop) {
      wx.showToast({
        title: '请先勾选已阅读说明内容',
        icon: "none",
      });
      return;
    }
    // 兑换操作
    let urlStr = app.getNetAddresss("plugin.share-chain.frontend.exchange.handle");
    urlStr += "&source_code=" + this.data.activeName + "&queue_id=" + this.data.chooseId + "&exchange_code=" + this.data.convertTypeId;
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        wx.showToast({
          title: res.data.msg,
          icon: "none",
        });
        if (res.data.result === 1) {
          res.data = res.data.data;
          this.setData({
            show3: false,
            showeforeSurePop: false
          });
          this.getData(this.data.activeName, "plugin.share-chain.frontend.queue.getList");
        } else {
          this.setData({
            show3: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  endReward() {
    this.setData({
      show4: false,
    });
  },
  exchangeLog(item) {
    let obj = item.currentTarget.dataset.item || item.target.dataset.item;
    let urlStr = app.getNetAddresss("plugin.share-chain.frontend.exchange.log");
    urlStr += "&source_code=" + this.data.activeName + "&queue_id=" + obj.id;
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          res.data = res.data.data;
          this.setData({
            show4: true,
            exchangeLogs: res.data,
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  luckyDraw(item) {
    // 抽奖
    let itemse = item.currentTarget.dataset.item || item.target.dataset.item;
    this.setData({
      show1: true,
      chooseId: itemse.id,
      chooseRatio: itemse.ratio,
    });
  },
  sureTake(item) {
    // 确认抽奖
    // let itemsk = item.currentTarget.dataset.item || item.target.dataset.item
    let urlStr = app.getNetAddresss("plugin.share-chain.frontend.lucky.handle");
    urlStr += "&source_code=" + this.data.activeName + "&queue_id=" + this.data.chooseId;
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          res.data = res.data.data;
          this.setData({
            show1: false,
            show2: true,
            msg: res.data.msg,
          });
          this.getData(this.data.activeName, "plugin.share-chain.frontend.queue.getList");
        } else {
          this.setData({
            show1: false,
          });
          wx.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 取消抽奖
  sureTakere() {
    this.setData({
      show1: false,
    });
  },
  getUser() {
    let urlStr = app.getNetAddresss("plugin.share-chain.frontend.member.getInfo");
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          res.data = res.data.data;
          this.setData({
            nickname: res.data.nickname,
            avatar: res.data.avatar,
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getHomeInfo() {
    let urlStr = app.getNetAddresss("plugin.share-chain.frontend.center.statistics");
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          res.data = res.data.data;
          this.setData({
            summarizing: res.data,
          });
          if (this.data.summarizing.label_order) {
            this.data.label_order = Object.entries(this.data.summarizing.label_order)
              .sort((a, b) => b[1] - a[1])
              .map(entry => entry[0]);
            this.setData({
              label_order: this.data.label_order
            })
          }
          if (this.data.label_order.length > 0) {
            if (this.data.label_order[0] == "cashier") {
              this.setData({
                activeName: 'cashier'
              })
            } else if (this.data.label_order[0] == "store") {
              this.setData({
                activeName: 'store'
              })
            } else if (this.data.label_order[0] == "shop") {
              this.setData({
                activeName: 'shop'
              })
            }
            this.getData(this.data.activeName, "plugin.share-chain.frontend.queue.getList");
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  handleClick1(tab) {
    if (tab.detail.index == 0) {
      this.setData({
        chooseName: "queue",
      });
      this.getData(this.data.activeName, "plugin.share-chain.frontend.queue.getList");
    } else if (tab.detail.index == 1) {
      this.setData({
        chooseName: "record",
      });
      this.getData("", "plugin.share-chain.frontend.log.getList");
    }
  },
  handleClick(e) {
    console.log(e, 'wwwwwwwwww');
    let {
      item
    } = e.currentTarget.dataset;
    this.setData({
      activeName: item
    })
    // if (this.data.label_order[tab.detail.index] == 'shop') {
    //   this.setData({
    //     activeName: "shop",
    //   });
    // } else if (this.data.label_order[tab.detail.index] == 'store') {
    //   this.setData({
    //     activeName: "store",
    //   });
    // } else if (this.data.label_order[tab.detail.index] == 'cashier') {
    //   this.setData({
    //     activeName: "cashier",
    //   });
    // }
    this.getData(this.data.activeName, "plugin.share-chain.frontend.queue.getList");
  },
  // 获取数据
  getData(status, api) {
    if (app.globalData.STORE_ID) {
      // 门店独立模板的共享链接口改变
      if (api == 'plugin.share-chain.frontend.queue.getList') {
        api = "plugin.share-chain.frontend.storeAloneTemp.queue.getList";
      } else if (api == 'plugin.share-chain.frontend.log.getList') {
        api = "plugin.share-chain.frontend.storeAloneTemp.log.getList";
      }
    }
    this.setData({
      getDataApi: api,
      status: status,
    });
    let urlStr = app.getNetAddresss(api);
    urlStr += "&source_code=" + status;
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        if (res.data.result === 1) {
          res.data = res.data.data;
          this.setData({
            isLoadMore: true,
            total_page: res.data.last_page,
            rewardList: res.data.data,
            is_queue_process: res.data.is_queue_process,
            is_awaiting_rewards: res.data.is_awaiting_rewards,
            is_queue_id: res.data.is_queue_id,
            is_queue_line_up: res.data.is_queue_line_up
          });
          if (!this.data.total_page) {
            this.setData({
              total_page: 0,
            });
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 1500,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateTo({
                  url: "/packageG/pages/member/extension/extension",
                });
              }, 1500); //延迟时间
            },
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 获取更多数据
  getMoreData() {
    this.setData({
      isLoadMore: false,
    });
    let urlStr = app.getNetAddresss(this.data.getDataApi);
    let pages = this.data.page + 1;
    this.setData({
      page: pages,
    });
    if (this.data.status) {
      urlStr += "&source_code=" + this.data.status + "&page=" + this.data.page;
    } else {
      urlStr += "&page=" + this.data.page;
    }
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      app._getNetWork({
        url: urlStr,
        success: (res) => {
          if (res.data.result === 1) {
            res.data = res.data.data;
            let myData = this.data.rewardList.concat(res.data.data);
            this.setData({
              isLoadMore: true,
              rewardList: myData,
            });
          } else {
            let pageOne = this.data.page - 1;
            this.setData({
              page: pageOne,
              isLoadMore: false,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  onChangeSurePopChecked(event) {
    this.setData({
      checkedSurePop: event.detail,
    });
  },
  async get_statistics_STORE() {
    let strUrl = "";
    if (app.globalData.STORE_ID) {
      strUrl = app.getNetAddresss("plugin.share-chain.frontend.storeAloneTemp.center.statistics")
    } else {
      strUrl = app.getNetAddresss("plugin.share-chain.frontend.center.statistics")
    }
    let {
      data
    } = await app._postNetWork({
      url: strUrl
    })
    if (data.result) {
      wx.setNavigationBarTitle({
        title: data.data.plugin_name ? data.data.plugin_name : "",
      });
      this.setData({
        summarizing: data.data,
        rule_desc: data.data.rule_desc
      });
      if (this.data.summarizing.label_order) {
        this.data.label_order = Object.entries(this.data.summarizing.label_order)
          .sort((a, b) => b[1] - a[1])
          .map(entry => entry[0]);
        this.setData({
          label_order: this.data.label_order
        })
      }
      if (this.data.label_order.length > 0) {
        if (this.data.label_order[0] == "cashier") {
          this.setData({
            activeName: 'cashier'
          })
        } else if (this.data.label_order[0] == "store") {
          this.setData({
            activeName: 'store'
          })
        } else if (this.data.label_order[0] == "shop") {
          this.setData({
            activeName: 'shop'
          })
        }
        if (app.globalData.STORE_ID) {
          this.getData(this.data.activeName, "plugin.share-chain.frontend.storeAloneTemp.queue.getList");
        } else {
          this.getData(this.data.activeName, "plugin.share-chain.frontend.queue.getList");
        }
      }
      this.setData({
        plugin_name: data.data.plugin_name,
        nickname: data.data.member.nickname,
        avatar: data.data.member.avatar,
      })
    } else {
      app.tips(data.msg);
    }
  },
  toQueueDetail(e) {
    let { isto, queue_id } = e.currentTarget.dataset;
    if(!isto) return;
    let extparams = {
      queue_id,
      avg_reward_type: this.data.activeName
    };
    let url = `/mircoApp/shop_base/reward_template/index?api=plugin.share-chain.frontend.reward-total-detail.index&extparams=${JSON.stringify(extparams)}`
    wx.navigateTo({
      url: url,
    });
  }
});